package com.yunhan.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunhan.base.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.io.IOException;

@Slf4j
public class ResponseUtil {

    public static void out(HttpServletResponse response, R r) {
        ObjectMapper mapper = new ObjectMapper();
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            mapper.writeValue(response.getWriter(), r);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }


    //向浏览器响应数据
    public static void writeResponse(HttpServletResponse resp, Integer code, String message) {
        try{
            resp.setContentType("application/json;charset=utf-8");
            resp.reset();

            R<String> r = R.fail(code, message);
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(r);

            // 写出去
            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.write(s.getBytes());
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}